from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from libs.captcha.captcha import captcha

from random import randint

# Create your views here.
class ImageCodeView(View):

    def get(self, request, uuid):
        # 接收前端传过来的uuid
        # 生成图片验证码和图片二进制
        text, image = captcha.generate_captcha()
        # 把数据存入redis
        from django_redis import get_redis_connection


        redis_cli = get_redis_connection('code')
        redis_cli.setex(name=uuid, time=100, value=text)

        return HttpResponse(image, content_type='image/jpeg')

# 图片验证码接入，发送短信
class SmsCodeView(View):
    def get(self, request, mobile):
        # 取出查询字符串的图片验证码值和uuid
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 判断他们是否存在
        if not ([image_code, uuid]):
            return JsonResponse({'code': 404, 'data': '参数不全'})

        # 连接redis
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        pipeline = redis_cli.pipeline
        # 取出redis中图片验证码的数值
        old_image_code = redis_cli.get(uuid)
        if old_image_code is None:
            return JsonResponse({'code': 404, 'data': '验证码已过期'})
        # 判断redis中的数据与用户还过来的值是否相等
        if image_code.lower() != old_image_code.decode().lower():
            return JsonResponse({'code': 404, 'data': '验证码输入错误'})
        # 产生随机码并存入redis

        # 判断标志验证码是否存在
        if redis_cli.get('flag_%d' % mobile):
            return JsonResponse({'code': 400, 'errmsg': '不要重复发送验证码'})

        sms_code = '%06d' % randint(0, 999999)
        # pipeline.incr(name=mobile, time=300, value=sms_code)
        redis_cli.setex(name=mobile, time=300, value=sms_code)
        print(sms_code)
        # pipeline.execute()

        # 发送验证码
        from celery_tasks.sms.tasks import celery_send_sms
        from libs.yuntongxun.sms import CCP
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        celery_send_sms.delay(mobile, [sms_code, 5])
        # 存进redis一个标记。如果存在就告知前端，前端返回重复请勿点击发送验证码
        redis_cli.setex('flag_%d' % mobile, 60, 2)
        return JsonResponse({'code': 0, 'data': 'ok'})




